// 引入包
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const router = require('./router.js')
const JWT = require('./token.js')
// const tokenFn = require('../src/utils//token')
// const { expressjwt: jwt } = require('express-jwt')
// const JWT = require('./token.js')
// 创建服务器
const app = express()

app.options('/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
  res.sendStatus(200)
})

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  next()
})

// 排除 login 相关的路由和接口
app.use((req, res, next) => {
  if (req.url.includes('login')) {
    next()
    return
  }
  // 获取token
  const token = req.headers.authorization?.split(' ')[1]
  if (token) {
    // 校验 token
    const payload = JWT.verifyToken(token)
    // console.log(payload)
    if (payload) {
      // 重新计算 token 过期时间
      const newToken = JWT.encryptionToken({ data: payload.data }, '6h')
      res.header('Authorization', newToken)
      next()
    } else {
      res.status(401).send({ errCode: -1, err: 'token 过期' })
    }
  } else {
    next()
  }
})

app.use(bodyParser.json({ limit: '50mb' })) // 解析json和urlendcoded格式数据
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
app.use(cors())
app.use(router)

app.listen(3005, () => {
  console.log('http://127.0.0.1:3005', '服务器启动成功')
})
